package com.xinziruo.crawl.infrastruture.support.codec;

import static com.xinziruo.crawl.infrastruture.support.command.CommandConstant.*;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.xinziruo.crawl.infrastruture.support.command.Command;
import com.xinziruo.crawl.infrastruture.support.command.CommandConverter;
import com.xinziruo.crawl.infrastruture.support.command.impl.IoBufferCommandConverter;

/**
 * 
 * @author loudyn
 * 
 */
public class CommandProtocolDecoder extends CumulativeProtocolDecoder {

	private CommandConverter<IoBuffer> converter = new IoBufferCommandConverter();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org.apache.mina.core.session.IoSession,
	 * org.apache.mina.core.buffer.IoBuffer, org.apache.mina.filter.codec.ProtocolDecoderOutput)
	 */
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

		// 5m
		if (!in.prefixedDataAvailable(CONTENT_LENGTH_BYTES, 5 * 1024 * 1024)) {
			return false;
		}

		Command comm = converter.toCommand(in);
		out.write(comm);
		return true;
	}

}
